#ifndef MYUI_H_INCLUDED
#define MYUI_H_INCLUDED
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <conio.h>
#include "User.h"
#include "FinanceManage.h"
#include "Finance.h"
#include <time.h>
#include <algorithm>

//宏定义
#define EXIT_PAGE INT_MIN
#define SHOW_FINANCE_4REMOVE_PRE -8
#define REMOVE_FINANCE_PAGE -7
#define SHOW_FINANCE_PAGE -6
#define APPLY_HANDLE_PAGE -5
#define ADD_FINANCE_PAGE -4
#define SHOW_USERS_PAGE -3
#define REMOVE_USER_PAGE -2
#define ADD_USER_PAGE -1
#define LOGIN 0
#define MAIN_PAGE 1
#define PW_MODIFY_PAGE 2
#define APPLY_FINANCE_PAGE 3
#define REPORT_BY_MONTH_PAGE 4
#define REPORT_BY_TERM_PAGE 5
#define APPLY_CHECK_PAGE 6
#define ERROR_PAGE INT_MAX


using namespace std;
/*

        对界面进行绘制，根据用户操作调用对应方法
*/
class MyUI
{
public:
        UserManage *userManage;
        FinanceManage * financeManage;
        FinanceManage * applyFinanceManage;
        FinanceManage * acceptedList;
        User *currentUser = NULL;
        MyUI(UserManage *_userManage, FinanceManage * _financeManage, FinanceManage * _applyFinanceManage,FinanceManage * _uncheckList)
        {
                applyFinanceManage = _applyFinanceManage;
                financeManage = _financeManage;
                userManage = _userManage;
                acceptedList = _uncheckList;
        }

        /**
                调用其它页面并且返回下一页面id
        */
        int UIdispatcher(int n)
        {


                switch (n)
                {
                case LOGIN:
                        currentUser = login();
                        if (isLoginSuccess())
                        {
                                return MAIN_PAGE;
                        }
                        else
                        {
                                cout << "\n账号或者密码错误！\n";
                                system("pause");
                                return LOGIN;
                        }
                        break;
                case MAIN_PAGE:
                        return paintMain();
                        break;
                case ADD_USER_PAGE:
                        return addUserUI();
                        break;
                case SHOW_USERS_PAGE:
                        return showAllUsers(1);
                        break;
                case PW_MODIFY_PAGE:
                        return modifyUser();
                        break;
                case ADD_FINANCE_PAGE:
                        return addFinance();
                        break;
                case APPLY_FINANCE_PAGE:
                        return applyFinance();
                        break;
                case APPLY_HANDLE_PAGE:
                        return applyHandle();
                        break;
                case SHOW_FINANCE_PAGE:
                        return showAllFinance();
                        break;
                case REMOVE_USER_PAGE:
                        return removeUserUI();
                        break;
                case REMOVE_FINANCE_PAGE:
                        return removeFinanceUI();
                        break;
                case SHOW_FINANCE_4REMOVE_PRE:
                        return showAllFinance(true);
                        break;
                case REPORT_BY_MONTH_PAGE:
                        return reportByMonth();
                        break;
                case REPORT_BY_TERM_PAGE:
                        return reportByTerm();
                        break;
                case APPLY_CHECK_PAGE:
                        return applyCheck();
                        break;
                default:
                        break;

                }

        }
        /**
                主界面
        */
        int paintMain()
        {
                User *user = currentUser;
                system("cls");
                string lvName;
                if ((*user).level == 1)
                {
                        lvName = " 管理员";
                }
                else
                {
                        lvName = " 同学";
                }
                cout << "您好， " << (*user).uid << lvName << endl;
                paint("UI\\mainUI.txt");
                if ((*user).level == 1)
                {
                        paint("UI\\mainUIAdmin.txt");
                }
                else
                {
                        paint("UI\\mainUInormal.txt");
                }

                int fid = 0;
                cout << "请输入对应数字选择功能：";
                cin >> fid;
                fid = (*user).level == 1 ? -fid : fid;

                switch (fid)
                {
                case 0:
                        return LOGIN;
                        break;
                case 1:
                        return REPORT_BY_TERM_PAGE;
                        break;
                case 2:
                        return PW_MODIFY_PAGE;
                        break;
                case 3:
                        return APPLY_FINANCE_PAGE;
                        break;
                case 4:
                        return APPLY_CHECK_PAGE;
                        break;
                case -1:
                        return REPORT_BY_TERM_PAGE;
                        break;
                case -2:
                        return PW_MODIFY_PAGE;
                        break;
                case -3:
                        return APPLY_HANDLE_PAGE;
                        break;
                case -4:
                        return ADD_FINANCE_PAGE;
                        break;
                case -5:
                        return SHOW_FINANCE_PAGE;
                        break;
                case -6:
                        return REMOVE_FINANCE_PAGE;
                        break;
                case -7:
                        return SHOW_USERS_PAGE;
                        break;
                case -8:
                        return ADD_USER_PAGE;
                        break;
                case -9:
                        return REMOVE_USER_PAGE;
                        break;
                default:
                        cout << "未知选项！\n";
                        system("pause");
                        return MAIN_PAGE;
                        break;
                }
                return 0;
        }
        /**

               @return 输出TXT中的字符
        */
        void paint(string filePath)
        {
                ifstream fin;
                string buf = "";
                fin.open(filePath.c_str(), ios_base::in | ios_base::binary);
                if (fin.is_open())
                {
                        while (getline(fin, buf))
                        {
                                cout << buf << endl;
                        }
                        fin.close();
                }
        }


        /**
                进行密码的输入
                读取成功返回string对象的地址
                如果读取失败（超过64个字符）则返回NULL
        */
        static string * readPassword()
        {
                char * pw = new char[70];
                char ch;
                int i = 0;
                while ((ch = _getch()) != '\r')
                {
                        if (ch == '\b' && i > 0)
                        {
                                printf("\b \b");
                                --i;
                        }
                        else if (ch != '\b')
                        {
                                pw[i++] = ch;
                                printf("*");
                        }
                        if (i > 64)
                        {
                                cout << endl << "警告！密码不允许超过64位" << endl;
                                system("pause");
                                return NULL;
                        }
                }
                pw[i] = '\0';
                printf("\n");
                string *strpw = new string(pw);
                return strpw;

        }
        /**
                提供所有用户用于修改密码
        */
        int modifyUser()
        {
                system("cls");
                paint("UI\\modifyUserUI.txt");
                User * user = currentUser;
                cout << "当前用户名：" << user->uid << endl;
                cout << "用户等级：" << user->level << endl;
                cout << "是否要修改密码(y/n)：";
                string flag = "";
                cin >> flag;
                if (flag != "y")
                {
                        return MAIN_PAGE;
                }
                cout << "请输入新密码：";
                string* newPW1 = readPassword();
                cout << "请再次确认密码：";
                string* newPW2 = readPassword();
                if (newPW1->compare(*newPW2) != 0)
                {
                        cout << "两次密码不相同\n";
                        system("pause");
                        return PW_MODIFY_PAGE;
                }
                user->pw = *newPW1;
                userManage->save();
                return MAIN_PAGE;
        }
        /**
                进行登陆界面绘制与登陆验证方法调用
           @return     登陆成功返回User对象
                登陆失败返回NULL
        */
        User* login()
        {
                userManage->deleteUselessUser();
                system("cls");
                paint("UI\\loginUI.txt");
                cout << "请输入用户名：";
                string userName;
                cin >> userName;
                cout << "请输入密  码：";
                string * password = readPassword();
                if (password == NULL)
                {
                        return NULL;
                }
                return (*userManage).loginCheck(userName, *password);
        }

        /**
                提供给管理员进行增加用户的界面
                @return 返回值下一个页面代码
        */
        int addUserUI()
        {
                system("cls");
                string flag, uid;
                int level = 0;
                string *pw;
                paint("UI\\addUserUI.txt");
                cout << "是否要添加新用户(y/n):";
                cin >> flag;
                if (flag != "y")
                {
                        return MAIN_PAGE;
                }
                cout << "请输入新用户的用户名：";
                cin >> uid;
                if (userManage->searchByUid(uid) != NULL)
                {
                        cout << "已经存在该用户!\n";
                        system("pause");
                        return ADD_USER_PAGE;
                }
                cout << "请输入新用户的密码：";
                pw = readPassword();
                cout << "上述信息输入正确？(y:继续,n:重新输入)";
                cin >> flag;
                if (flag != "y")
                {
                        return ADD_USER_PAGE;
                }
                cout << "请输入新用户的权限(0为普通用户，1为管理员用户)：";
                cin >> level;
                if (level == 1)
                {
                        cout << "警告！你正在将管理员权限赋予新用户！\n";
                        cout << "请再次确认(y/n):";
                        cin >> flag;
                        if (flag != "y")
                        {
                                level = 0;
                                cout << "赋予普通用户权限";
                        }
                        else
                        {
                                cout << "赋予管理员用户权限";
                        }
                }
                User * newUser = new User;
                newUser->uid = uid;
                newUser->pw = *pw;
                newUser->level = level;
                string currentUid = currentUser->uid;
                string currentPw  =currentUser->pw;

                userManage->add(newUser);
                cout << "\n成功！\n";
                system("pause");
                currentUser=userManage->loginCheck(currentUid,currentPw);
                return MAIN_PAGE;
        }
        /**
                向管理员展示用户列表
                @param ifCls 是否执行屏幕清空
        */
        int showAllUsers(bool ifCls)
        {

                if (ifCls == true)
                {
                        system("cls");
                }
                printTopMsg();
                paint("UI\\showUsersUI.txt");
                userManage->printAllUserFormal();
                /*
                cout<<"test";
                vector <User> copyVector = userManage->allUsers;
                cout<<"\norigin size= "<< userManage->allUsers.size()<<"\n copyVector size = "<<copyVector.size();
                */
                system("pause");
                return MAIN_PAGE;
        }

        int addFinance()
        {
                system("cls");
                string flag = "";
                Finance * temFinance;
                int type;
                double amount;
                string date;
                string description;
                string purpose = "";
                string applicant;
                bool dateFormatCheckFlag = false;

                paint("UI\\addFinanceUI.txt");
                cout << "请问是否要增加财务记录？(y/n)：";
                cin >> flag;
                if (flag != "y")
                {
                        return MAIN_PAGE;
                }
                cout << "请选择类型 支出填写-1 收入填写 1(-1/1)";
                cin >> type;
                if (type > 1 || type < -1)
                {
                        cout << "错误的范围\n";
                        system("pause");
                        return ADD_FINANCE_PAGE;
                }
                if (type == -1) //支出才需要填写资金用途
                {
                        cout << "请输入资金的用途(请填写词语，例如：娱乐、学习。会作为统计分类的依据):";
                        while (purpose == "")
                        {
                                cin >> purpose;
                                if (purpose == "")
                                {
                                        cout << "用途不能为空";
                                }
                        }
                }
                else
                {
                        purpose = "";
                }
                cout << "请输入这条信息的描述：";
                fflush(stdin);//吃掉回车
                getline(cin, description);
                while (!dateFormatCheckFlag)
                {
                        cout << "请输入记录时间 (格式yyyy-mm-dd,或者输入current代表当前时间)：";
                        cin >> date;
                        if (date == "current")
                        {
                                date = getCurrentDate();
                        }
                        int year, month, day;
                        sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day);
                        dateFormatCheckFlag = checkDate(year, month, day);
                        if (dateFormatCheckFlag == false)
                        {

                                cout << "时间格式有误,请重新输入\n";
                                fflush(stdin);
                        }
                }
                cout << "请输入数量(单位rmb)：";
                cin >> amount;
                cout << "请输入 申请者(支出)/相关人员(收入) 姓名:";
                cin >> applicant;
                cout << "请确认以上信息是否录入正确(y/n)：";
                cin >> flag;
                if (flag != "y")
                {
                        return ADD_FINANCE_PAGE;
                }
                temFinance = new Finance;
                temFinance->amount = amount;
                temFinance->applicant = applicant;
                temFinance->date = date;
                temFinance->description = description;
                temFinance->purpose = purpose;
                temFinance->type = type;
                financeManage->add(temFinance);

                return MAIN_PAGE;
        }

        /**

        */
        int applyFinance()
        {
                system("cls");
                string flag = "";
                double amount = 0;
                string purpose = "";
                string description = "";
                string applicant = currentUser->uid;
                string date = getCurrentDate();


                int type = -1; //默认为支出
                printTopMsg();
                paint("UI\\applyFinanceUI.txt");
                cout << "是否要进行资金申请(y/n):";
                cin >> flag;
                if (flag != "y")
                {
                        return MAIN_PAGE;
                }
                cout << "请输入资金数目(单位rmb)：";
                cin >> amount;
                cout << "请输入资金的用途(请填写词语，例如：娱乐、学习。会作为统计分类的依据):";
                while (purpose == "")
                {
                        cin >> purpose;
                        if (purpose == "")
                        {
                                cout << "用途不能为空";
                        }
                }
                cout << "请输入这条信息的描述(一行)：";
                fflush(stdin);//吃掉回车
                getline(cin, description);
                cout << "请确认以上信息输入正确(y/n):";
                cin >> flag;
                if (flag != "y")
                {
                        return APPLY_FINANCE_PAGE;
                }
                Finance * temFinance = new Finance;
                temFinance->amount = amount;
                temFinance->applicant = applicant;
                temFinance->date = date;
                temFinance->description = description;
                temFinance->purpose = purpose;
                temFinance->type = type;
                applyFinanceManage->add(temFinance);
                cout << "\n申请信息已录入\n";
                system("pause");
                return APPLY_CHECK_PAGE;
        }
        /**
                管理员处理来自普通用户的资金申请



        */
        int applyHandle()
        {
                system("cls");
                printTopMsg();
                paint("UI\\applyHandleUI.txt");
                string inputText;

                cout << "接收到请求：\n";
                int applyCount = applyFinanceManage->printAllFinanceFormal();
                cout << "\n\t共 " << applyCount << " 条请求\n\n";

                cout << "您可以进行以下操作：\n";
                cout << "\t一、输入对应index代表接受该请求，并且录入数据\n";
                cout << "\t二、输入\"deleteAll\"代表拒绝剩余所有请求\n";
                cout << "\t三、输入\"exit\"回到主界面\n\n";
                cout << "等待命令:";
                cin >> inputText;

                if (inputText == "deleteAll")
                {
                        string selection;
                        cout << "真的要删除所有资金请求吗?(y/n):";
                        cin >> selection;
                        if (selection != "y")
                        {
                                return APPLY_HANDLE_PAGE;
                        }
                        applyFinanceManage->allFinances.clear();
                        applyFinanceManage->save();
                }

                if (inputText == "exit")
                {
                        return MAIN_PAGE;
                }
                const char * chrs = inputText.c_str();
                int textLength = inputText.size();
                bool flag = true;
                //确定由数字组成
                for (int i = 0; i < textLength; i++)
                {
                        if (chrs[i] > '9' || chrs[i] < '0')
                        {
                                flag = false;
                                break;
                        }
                }

                // inputText is rownum
                int permitedRownum = atoi(inputText.c_str());
                if (permitedRownum >= applyCount || permitedRownum < 0 || flag == false)
                {
                        cout << "请输入正确的指令!\n";
                        system("pause");
                        return APPLY_HANDLE_PAGE;
                }
                string selection;
                cout << "真的要录入该资金请求吗?(y/n):";
                cin >> selection;
                if (selection != "y")
                {
                        return APPLY_HANDLE_PAGE;
                }
                financeManage->add(&applyFinanceManage->allFinances[permitedRownum]);
                acceptedList->add(&applyFinanceManage->allFinances[permitedRownum]);
                applyFinanceManage->rm(permitedRownum);

                return APPLY_HANDLE_PAGE;
        }

        /**
        * 展示所有的资金记录
        * 当wantDelete=true时进行删除相关操作
        */
        int showAllFinance(bool wantDelete = false)
        {

                system("cls");
                printTopMsg();
                paint("UI\\showAllFinanceUI.txt");
                string yearStr;
                int year;
                cout<<"\t请输入年份,查询对应年份记录 例如:2016\n\t输入LIKE开启模糊查询模式\n\t输入exit or -1退出\n";
                cout << "等待输入:";
                cin >> yearStr;
                year = atoi(yearStr.c_str());
                if(yearStr=="LIKE"||yearStr=="like"){
                        cout<<"请输入模糊查询关键字,例如:\"收入\"、\"支出\"、姓名、时间、用途等\nkeyword=";
                        string keyword;
                        cin>>keyword;
                        financeManage->printFinancesFilter([&](Finance x){
                                if(x.description.find(keyword)!=-1){
                                        return true;
                                }
                                if(x.purpose.find(keyword)!=-1){
                                        return true;
                                }
                                if(keyword.find(x.applicant)!=-1){
                                        return true;
                                }
                                if(x.date.find(keyword)!=-1){
                                        return true;
                                }
                                if(keyword=="收入"){
                                        if(x.type==1){
                                                return true;
                                        }
                                }
                                if(keyword=="支出"){
                                        if(x.type==-1){
                                                return true;
                                        }
                                }
                                return false;
                        });
                        system("pause");


                        return SHOW_FINANCE_PAGE;
                }
                if (year == -1 || yearStr == "exit")
                {
                        return MAIN_PAGE;
                }
                if (year > 9999 || year < 1 || !checkConsistOfNumber(yearStr))
                {
                        cout << "错误的年份\n";
                        system("pause");
                        return SHOW_FINANCE_PAGE;
                }

                char timePre[100];
                sprintf(timePre, "%d-12-31", year - 1);
                char timeThis[100];
                sprintf(timeThis, "%d-12-31", year);
                int counter = financeManage->printFinancesFilter([&](Finance fi)
                {
                        return fi.date > timePre && fi.date <= timeThis;
                });
                if (counter == 0)
                {
                        cout << "\n找不到记录";
                }
                else
                {
                        cout << "\n\t\t共 " << counter << " 条记录";
                }
                cout << "\n\n";
                system("pause");
                if (wantDelete == true)
                {
                        cout << "查询完成，是否要开始删除？(y/n):";
                        string selection;
                        cin >> selection;
                        if (selection == "y")
                        {
                                return REMOVE_FINANCE_PAGE;
                        }
                        return SHOW_FINANCE_4REMOVE_PRE;
                }
                return SHOW_FINANCE_PAGE;
        }
        /**
                提供给管理员 根据index删除finance记录
        */
        int removeFinanceUI()
        {
                system("cls");
                printTopMsg();

                printSplitLine();
                cout << "\n\n";
                cout << "				    删除资金记录";


                {
                        cout << "\n\n\t是否开始删除资金记录？(y/n):";
                        string selection;
                        cin >> selection;
                        if (selection != "y")
                        {
                                return MAIN_PAGE;
                        }
                }
                cout << "\n\n\t依据index删除资金记录\n\t您已经知道目标index吗?(y/n)(开始删除/进行查询)：";

                string selection;
                cin >> selection;
                if (selection != "y")
                {
                        return SHOW_FINANCE_4REMOVE_PRE;
                }
                cout << "\n\t请输入要删除记录的index(-1退出):";
                int index;
                cin >> index;
                if (index == -1)
                {
                        return MAIN_PAGE;
                }
                if (financeManage->rm(index) == true)cout << "删除成功";
                else cout << "删除失败";
                cout << endl;
                system("pause");


                return MAIN_PAGE;

        }
        /**
                提供给管理员用户使用，根据用户id删除用户
        */
        int removeUserUI()
        {
                system("cls");
                printTopMsg();
                printSplitLine();
                cout << "\n\n\t用户列表：\n\n";
                userManage->printAllUserFormal();
                cout << "\n输入对应rownum可以删除用户(-1 or exit退出):";
                string inputStr;
                cin >> inputStr;
                int input;
                input = atoi(inputStr.c_str());
                if (input == -1 || inputStr == "exit")
                {
                        return MAIN_PAGE;
                }
                int length = userManage->allUsers.size();
                if (input < 0 || input >= length || !checkConsistOfNumber(inputStr))
                {
                        cout << "输入错误的数字\n";
                        system("pause");
                        return REMOVE_USER_PAGE;
                }
                cout << "\n您选定要删除的用户 " << userManage->allUsers[input].uid << endl;
                string selection;
                cout << "确认删除该用户(y/n):";
                cin >> selection;
                if (selection != "y")
                {
                        return REMOVE_USER_PAGE;
                }
                userManage->rm(input);
                cout << "\n删除成功\n";
                system("pause");
                return REMOVE_USER_PAGE;
        }
        /**
                依据月份产生报告

                提供控制条 按月份分页
        */
        int reportByMonth(string dateL = "", string dateR = "")
        {
reportByMonthfunctionStart:

                system("cls");
                printTopMsg();
                paint("UI\\reportByMonth.txt");
                if (dateL == "")
                {
                        int day = atoi(getCurrentDate().substr(8, 2).c_str()) + 1;
                        char tem[100] = {0};
                        sprintf(tem, "%02d", day);
                        dateL = getCurrentDate().substr(0, 8) + "01";
                        dateR = getCurrentDate().substr(0, 8) + tem;
                }
                cout << "  您现在查看的是 [" << dateL << " , " << dateR << ")的统计" << endl << endl;
                vector<Finance> * ans = financeManage->getFinancesLimitDate(dateL,
                                        dateR);

                int ansLength = ans->size();
                if (ansLength == 0)
                {
                        cout << "没有数据";
                }
                else
                {
                        //有数据的时候
                        double income = 0, costSum = 0;
                        sort((*ans).begin(), (*ans).end(), [&](Finance x, Finance y)
                        {
                                return x.purpose < y.purpose;
                        });
                        for (int i = 0; i < ansLength; i++)
                        {
                                //cout << "data date - " << (*ans)[i].date << endl;
                                if ((*ans)[i].type == 1)income += (*ans)[i].amount;
                                else costSum += (*ans)[i].amount;
                        }
                        cout << "本月收入： " << income << " 本月支出:  " << costSum << endl;
                        cout << "本月盈亏:  " << income - costSum << endl;

                        //按purpose整合
                        int father[500] = {0};
                        Finance list4Purpose[500];
                        int listp = 0;
                        for (int i = 0; i < ansLength; i++)
                        {
                                father[i] = i;
                        }

                        for (int i = 0; i < ansLength; i++)
                        {
                                if (i == 0)
                                {
                                        list4Purpose[listp++] = (*ans)[0];
                                        list4Purpose[listp - 1].amount *= list4Purpose[listp - 1].type;
                                        continue;
                                }
                                if ((*ans)[i].purpose == (*ans)[i - 1].purpose)
                                {
                                        list4Purpose[father[i - 1]].amount += (*ans)[i].amount * (*ans)[i].type;
                                        father[i] = father[i - 1];
                                }
                                else
                                {
                                        list4Purpose[listp++] = (*ans)[i];
                                        list4Purpose[listp - 1].amount *= list4Purpose[listp - 1].type;
                                }
                        }
                        cout << "\n\t按照类型进行统计：\n\n";
                        for (int i = 0; i < listp; i++)
                        {
                                if (list4Purpose[i].type == 1)
                                        cout << "类型 ：收入" << "\t 变更金额 : +" << list4Purpose[i].amount << endl;
                                else cout << "类型 ：" << list4Purpose[i].purpose << "\t 变更金额 : " << list4Purpose[i].amount << endl;
                        }
                }
                cout << "\n\t\tL:上个月\tR:下个月\tterm:按学期统计\texit:退出\n";
                cout << "等待命令：";
                string inputText;
                string emptyStr = "";
                while (true)
                {
                        cin >> inputText;
                        if (inputText == "term")
                        {
                                return REPORT_BY_TERM_PAGE;
                        }
                        if (inputText == "L" || inputText == "l")
                        {
                                int currentMonth = atoi(dateL.substr(5, 2).c_str());
                                int currentYear  = atoi(dateL.substr(0, 4).c_str());
                                string emptyStr = "";
                                char tem[100] = { 0 };
                                if (currentMonth == 1)
                                {
                                        currentMonth = 13;
                                        currentYear--;
                                }
                                sprintf(tem, "%d-%02d-01", currentYear, currentMonth - 1);
                                dateR = dateL;
                                dateL = tem + emptyStr;
                                goto reportByMonthfunctionStart;
                        }
                        if (inputText == "R" || inputText == "r")
                        {
                                int currentMonth = atoi(dateL.substr(5, 2).c_str());
                                int currentYear  = atoi(dateL.substr(0, 4).c_str());
                                char tem[100] = { 0 };//BUG
                                if (currentMonth == 11)
                                {
                                        sprintf(tem, "%d", atoi(dateL.substr(0, 4).c_str()) + 1);
                                        string temYear = tem;
                                        sprintf(tem, "%02d", 1);
                                        dateR = temYear + "-" + tem + "-01";
                                        sprintf(tem, "%02d", 12);
                                        dateL = dateL.substr(0, 4) + "-" + tem + "-01";
                                }
                                else if (currentMonth == 12)
                                {
                                        sprintf(tem, "%d", atoi(dateL.substr(0, 4).c_str()) + 1);
                                        string temYear = tem;
                                        sprintf(tem, "%02d", 2);
                                        dateR = temYear + "-" + tem + "-01";
                                        sprintf(tem, "%02d", 1);
                                        dateL = temYear + "-" + tem + "-01";

                                }
                                else
                                {
                                        sprintf(tem, "%02d", currentMonth + 2);
                                        dateR = dateL.substr(0, 4) + "-" + tem + "-01";
                                        sprintf(tem, "%02d", currentMonth + 1);
                                        dateL = dateL.substr(0, 4) + "-" + tem + "-01";
                                }

                                goto reportByMonthfunctionStart;
                        }
                        if (inputText == "exit")
                        {
                                return MAIN_PAGE;
                        }
                }

                return MAIN_PAGE;

        }

        string getTermFibDate(int year)
        {
                char tem[100] = "";
                sprintf(tem, "%d", year);
                string temStr(tem);
                return temStr.append("-02-01");
        }
        string getTermSepDate(int year)
        {
                char tem[100] = "";
                sprintf(tem, "%d", year);
                string temStr(tem);
                return temStr.append("-09-01");
        }
        /**
         * isUpTerm=true时设置currentYear的9月份到nextYear的2月份
         * 否则设置currentYear的2月份-9月份
         */
        void setTermDate(string &dateL, string &dateR, int currentYear = -1,
                         bool isUpTerm = false)
        {
                if (isUpTerm == true)
                {
                        dateL = getTermSepDate(currentYear);
                        dateR = getTermFibDate(currentYear + 1);
                }
                else
                {
                        dateL = getTermFibDate(currentYear);
                        dateR = getTermSepDate(currentYear);
                }
        }
        int reportByTerm(int currentYear = -1, bool isUpTerm = false)
        {
reportByTermfunctionStart:
                {
                        //代码块


                        string dateL = "";
                        string dateR = "";
                        system("cls");
                        printTopMsg();
                        paint("UI\\reportByTerm.txt");

                        //取得当前学期界限
                        string currentDate = getCurrentDate();

                        if (currentYear == -1)
                        {
                                //上下学期判断
                                //对应9-月的情况
                                currentYear = atoi(currentDate.substr(0, 4).c_str());
                                isUpTerm = true;
                                setTermDate(dateL, dateR, currentYear, isUpTerm);
                                //对应不在2-9月和1-2月的情况
                                if (!(dateL <= currentDate && currentDate < dateR))
                                {
                                        isUpTerm = false;
                                        setTermDate(dateL, dateR, currentYear, isUpTerm);
                                        //对应1-2月的情况
                                        if (!(dateL <= currentDate && currentDate < dateR))
                                        {
                                                isUpTerm = true;
                                                currentYear--;
                                                setTermDate(dateL, dateR, currentYear, isUpTerm);
                                        }
                                }

                        }
                        else
                        {
                                setTermDate(dateL, dateR, currentYear, isUpTerm);
                        }
                        //统计
                        cout << "  您现在查看的是 [" << dateL << " , " << dateR << ")的统计" << endl << endl;
                        vector<Finance> * ans = financeManage->getFinancesLimitDate(dateL,
                                                dateR);
                        int ansLength = ans->size();
                        if (ansLength == 0)
                        {
                                cout << "\n\t没有数据！\n";
                        }
                        else
                        {
                                //有数据的时候
                                double income = 0, costSum = 0;
                                sort((*ans).begin(), (*ans).end(), [&](Finance x, Finance y)
                                {
                                        return x.purpose < y.purpose;
                                });
                                for (int i = 0; i < ansLength; i++)
                                {
                                        //cout << "data date - " << (*ans)[i].date << endl;
                                        if ((*ans)[i].type == 1)income += (*ans)[i].amount;
                                        else costSum += (*ans)[i].amount;
                                }
                                cout << "本学期收入： " << income << " 本学期支出:  " << costSum << endl;
                                cout << "本学期盈亏:  " << income - costSum << endl;

                                //按purpose整合
                                int father[500] = {0};
                                Finance list4Purpose[500];
                                int listp = 0;
                                for (int i = 0; i < ansLength; i++)
                                {
                                        father[i] = i;
                                }

                                for (int i = 0; i < ansLength; i++)
                                {
                                        if (i == 0)
                                        {
                                                list4Purpose[listp++] = (*ans)[0];
                                                list4Purpose[listp - 1].amount *= list4Purpose[listp - 1].type;
                                                continue;
                                        }
                                        if ((*ans)[i].purpose == (*ans)[i - 1].purpose)
                                        {
                                                list4Purpose[father[i - 1]].amount += (*ans)[i].amount * (*ans)[i].type;
                                                father[i] = father[i - 1];
                                        }
                                        else
                                        {
                                                list4Purpose[listp++] = (*ans)[i];
                                                list4Purpose[listp - 1].amount *= list4Purpose[listp - 1].type;
                                        }
                                }
                                cout << "\n\t按照类型进行统计：\n\n";
                                for (int i = 0; i < listp; i++)
                                {
                                        if (list4Purpose[i].type == 1)
                                                cout << "类型 ：收入" << "\t 变更金额 : +" << list4Purpose[i].amount << endl;
                                        else cout << "类型 ：" << list4Purpose[i].purpose << "\t 变更金额 : " << list4Purpose[i].amount << endl;
                                }



                        }
                }//代码块，防止变量声明冲突
                cout << "\n\t\tL:上一学期\tR:下一学期\tmonth:按月统计\texit:退出\n";
                cout << "等待命令：";
                string inputText;
                while (true)
                {
                        fflush(stdin);
                        cin >> inputText;
                        if (inputText == "L" || inputText == "l")
                        {
                                if (isUpTerm == true)
                                {
                                        currentYear = currentYear;
                                        isUpTerm = false;
                                        goto reportByTermfunctionStart;//回到函数顶部，模拟尾递归，防止stackOverFlow
                                        //下同
                                        //return reportByTerm(currentYear, false);
                                }
                                else
                                {
                                        currentYear = currentYear - 1;
                                        isUpTerm = true;
                                        goto reportByTermfunctionStart;
                                        //return reportByTerm(currentYear - 1, true);
                                }
                        }
                        if (inputText == "R" || inputText == "r")
                        {
                                if (isUpTerm == false)
                                {
                                        currentYear = currentYear;
                                        isUpTerm = true;
                                        goto reportByTermfunctionStart;
                                        //return reportByTerm(currentYear, true);
                                }
                                else
                                {
                                        currentYear = currentYear + 1;
                                        isUpTerm = false;
                                        goto reportByTermfunctionStart;
                                        //return reportByTerm(currentYear + 1, false);
                                }
                        }
                        if (inputText == "exit")
                        {
                                return MAIN_PAGE;
                        }
                        if (inputText == "month")
                        {
                                return REPORT_BY_MONTH_PAGE;
                        }
                }

                return MAIN_PAGE;
        }
        /**
                本方法负责展示自己的资金申请是否被录入
        */
        int applyCheck(){
                bool waitExist=true;
                system("cls");
                printTopMsg();
                printSplitLine();
                cout<<"				资金申请状态\n";
                vector<Finance> * ans ;
                ans = applyFinanceManage->financesFilter([&](Finance x){
                        return x.applicant==currentUser->uid;
                });
                int length =ans->size();
                if(length==0){
                        waitExist=false;
                }
                for(int i=0;i<length;i++){
                        applyFinanceManage->printSingleFinance(&(*ans)[i],"wait");
                }

                //accept
                ans = acceptedList->financesFilter([&](Finance x){
                return x.applicant==currentUser->uid;
                });
                length =ans->size();
                if(length==0&&!waitExist){
                        cout<<"\n\n\t无申请记录\n\n";
                }
                for(int i=0;i<length;i++){
                        acceptedList->printSingleFinance(&(*ans)[i],"accept");
                }

                cout<<endl;
                system("pause");
                return MAIN_PAGE;
        }

        int errorPage()
        {
                system("cls");
                cout << "\n\t\t产生不能被处理的错误！\n跳转至主界面";
                system("pause");
                return MAIN_PAGE;
        }

        //以下部分与UI无关

        bool isLoginSuccess()
        {
                if (currentUser == NULL) return false;
                else return true;
        }
        /**
                检查日期是否合法
        */
        bool checkDate(int year, int month, int day)
        {
                bool fcflag = false;
                if (year < 0 || year > 3000 || day > 31 || day < 0 || month > 12 || month < 0 )
                {
                        //printf("Please Input Right Number!\n");
                        return false;
                }
                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
                {
                        if (day > 0 && day <= 31)
                        {
                                fcflag = true;
                        }
                        else
                        {
                                fcflag = false;
                        }
                }

                else if (month == 2)
                {
                        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) && (year % 100 == 0))
                        {
                                if (day <= 29)
                                {
                                        fcflag = true;
                                }
                                else
                                {
                                        fcflag = false;
                                }
                        }
                        else
                        {
                                if (day <= 28)
                                {
                                        fcflag = true;
                                }
                                else
                                {
                                        fcflag = false;
                                }
                        }
                }
                else
                {
                        if (day > 0 && day < 31)
                        {
                                fcflag = true;
                        }
                        else
                        {
                                fcflag = false;
                        }
                }

                return fcflag;
        }
        /**
                取得当前时间
        */
        string getCurrentDate()
        {
                time_t rawtime = time(0);
                char   pblgtime[20];
                strftime(pblgtime, 20, "%Y-%m-%d", localtime(&rawtime));
                string currentTime(pblgtime);
                return currentTime;
        }

        /**
                打印顶部信息
                您好，xxx 同学/管理员
        */
        int printTopMsg()
        {
                User *user = currentUser;
                system("cls");
                string lvName;
                if ((*user).level == 1)
                {
                        lvName = " 管理员";
                }
                else
                {
                        lvName = " 同学";
                }
                cout << "您好， " << (*user).uid << lvName << endl;
                return 0;
        }
        void printSplitLine()
        {
                cout << "*-----------------------------------------------------------------------------*\n";
        }

        /**
                检测字符串是否完全由数字构成
        */
        bool checkConsistOfNumber(string str)
        {
                int length = str.size();
                bool flag = true;
                for (int i = 0; i < length; i++)
                {
                        if (!('0' <= str[i] && str[i] <= '9'))
                        {
                                flag = false;
                                break;
                        }
                }
                return flag;
        }


};

#endif // MYUI_H_INCLUDED
